﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WaterRevenueMS.WebUI.Common;
using System.ComponentModel.Composition;
using WaterRevenueMS.WebUI.Extension.Filters;
using WaterRevenueMS.Domain.Common.Models;
using WaterRevenueMS.Domain.ViewModels.BasicSet.CompanySet;
using WaterRevenueMS.Domain.ViewModels.BaseData;
using WaterRevenueMS.Componnent.Entities.BaseData;
using System.Linq.Expressions;
using WaterRevenueMS.WebUI.Extension.MvcHelper;
using WaterRevenueMS.Componnent.Common;
using WaterRevenueMS.Core.Service.BasicSet;
using WaterRevenueMS.Core.Service.BasicSet.Impl;
using WaterRevenueMS.Core.Service.BaseData;
using WaterRevenueMS.Core.Repository.BaseData;
using WaterRevenueMS.Domain.ViewModels.BaseData.Area;
using WaterRevenueMS.Domain.ViewModels.BaseData.MeterReader;
using System.Web.UI;

namespace WaterRevenueMS.WebUI.Controllers
{
    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class AreaController : AdminController
    {
        #region 属性
        [Import]
        public IMeterReaderService MeterReaderService { get; set; }

        [Import]
        public ICompanySetService CompanySetService { get; set; }

        [Import]
        public IAreaService AreaService { get; set; }
        
        #endregion


       [AdminLayoutAttribute]
        public ActionResult Index()
        {
            var model = new AreaModel();
            #region 单位信息
            var parentModuleData = CompanySetService.CompanySets.Where(t => t.IsDeleted == false)
            .Select(t => new AreaModel
            {
                CompanyId = t.Id,
                CompanyName = t.Dan_WMC
            });
            foreach (var item in parentModuleData)
            {
                model.Search.CompanyItems.Add(new SelectListItem { Text = item.CompanyName, Value = item.CompanyId.ToString() });
            }
            #endregion


            #region 抄表员信息
            var parentModuleDataa = MeterReaderService.MeterReaders.Where(t => t.IsDeleted == false)
            .Select(t => new AreaModel
            {
                ChaoBiao_ID = t.Id,
                CHao_B_Name = t.Chao_BYMC
            });
            foreach (var item in parentModuleDataa)
            {
                model.Search.ChaoBiaoItems.Add(new SelectListItem { Text = item.CHao_B_Name, Value = item.ChaoBiao_ID.ToString() });
            }
            #endregion

            return View(model);
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        public ActionResult List(DataTableParameter param)
        {
            int total = AreaService.Areas.Count(t => t.IsDeleted == false);

            var expr = BuildSearchCriteria();

            var filterResult = AreaService.Areas.Where(expr).Select(t => new AreaModel
            {
                id = t.Id,
                Qu_YMC = t.Qu_YMC,
                CompanyId =t.Dan_WSZ_No,
                CompanyName = t.CompanySet != null ? t.CompanySet.Dan_WMC : "",
                CHao_B_Name = t.MeterMan != null ? t.MeterMan.Chao_BYMC : "",
                ChaoBiao_ID = t.Chao_BY_No,
                Qu_YBH = t.Qu_YBH,
                OrderNo = t.OrderNo,

            }).OrderBy(t => t.id).Skip(param.iDisplayStart).Take(param.iDisplayLength).ToList();

            int sortId = param.iDisplayStart + 1;

            var result = from c in filterResult
                         select new[]
                        {
                            sortId++.ToString(), 
                            c.Qu_YMC,
                            c.Qu_YBH,
                            c.CompanyName,
                            c.CHao_B_Name,
                            c.ChaoBiao_ID.ToString(),
                            c.CompanyId.ToString(),
                            c.OrderNo.ToString(),

                            c.id.ToString()
                        };

            return Json(new
            {
                sEcho = param.sEcho,
                iDisplayStart = param.iDisplayStart,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Create()
        {
            var model = new AreaModel();
            InitAreaModel(model);
            return PartialView(model);
        }

        [AdminPermission(PermissionCustomMode.Ignore)]
        [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
        public JsonResult IsUnique_Available(string Qu_YBH)
        {
            if (!string.IsNullOrEmpty(Qu_YBH))
            {
                var entity = AreaService.Areas.FirstOrDefault(t => t.Qu_YBH == Qu_YBH);
                if (entity != null)
                {
                    //string message = "该用户编号已经存在";
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            return Json(true, JsonRequestBehavior.AllowGet);
        }


        [HttpPost]
        [AdminOperateLog]
        public ActionResult Create(AreaModel model)
        {
            if (ModelState.IsValid)
            {
                OperationResult result = AreaService.Insert(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }
            }
            else
            {
                return PartialView(model);
            }
           
        }

        public ActionResult Edit(int Id)
        {
            var model = new AreaModel();
            var entity = AreaService.Areas.FirstOrDefault(t => t.Id == Id);
            if (null != entity)
            {
                model = new AreaModel
                {
                    id = entity.Id,
                    Qu_YMC = entity.Qu_YMC,
                    Qu_YBH = entity.Qu_YBH,
                    CompanyId = entity.Dan_WSZ_No,
                    OrderNo = entity.OrderNo,
                    ChaoBiao_ID = entity.Chao_BY_No

                    
                };
            }
            InitAreaModel(model);
            return PartialView(model);
        }

        [HttpPost]
        public ActionResult Edit(AreaModel model)
        {
            if (ModelState.IsValid)
            {
                OperationResult result = AreaService.Update(model);
                if (result.ResultType == OperationResultType.Success)
                {
                    return Json(result);
                }
                else
                {
                    return PartialView(model);
                }

            }
            else
            {
                return PartialView(model);
            }
        }


        public ActionResult Delete(int Id)
        {
            OperationResult result = AreaService.Delete(Id);
            return Json(result);
        }


        private Expression<Func<Area, Boolean>> BuildSearchCriteria()
        {
            DynamicLambda<Area> bulider = new DynamicLambda<Area>();
            Expression<Func<Area, Boolean>> expr = null;
            if (!string.IsNullOrEmpty(Request["Qu_YMC"]))
            {
                var data = Request["Qu_YMC"].Trim();
                Expression<Func<Area, Boolean>> tmp = t => t.Qu_YMC.Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Qu_YBH"]) && Request["Qu_YBH"] != "0")
            {
                var data = Request["Qu_YBH"].Trim();
                Expression<Func<Area, Boolean>> tmp = t => t.Qu_YBH.ToString().Contains(data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }
            if (!string.IsNullOrEmpty(Request["Dan_WSZ_No"]) && Request["Dan_WSZ_No"] != "0")
            {
                var data = Convert.ToInt32(Request["Dan_WSZ_No"]);
                Expression<Func<Area, Boolean>> tmp = t => (t.Id == data) || (t.Dan_WSZ_No == data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }

            if (!string.IsNullOrEmpty(Request["Chao_BY_No"]) && Request["Chao_BY_No"] != "0")
            {
                var data = Convert.ToInt32(Request["Chao_BY_No"]);
                Expression<Func<Area, Boolean>> tmp = t => (t.Id == data) || (t.Chao_BY_No == data);
                expr = bulider.BuildQueryAnd(expr, tmp);
            }

            Expression<Func<Area, Boolean>> tmpSolid = t => t.IsDeleted == false;
            expr = bulider.BuildQueryAnd(expr, tmpSolid);

            return expr;
        }

        private void InitAreaModel(AreaModel model)
        {
            #region 单位信息
            var parentModuleData = CompanySetService.CompanySets.Where(t => t.IsDeleted == false)
            .Select(t => new AreaModel
            {
                CompanyId = t.Id,
                CompanyName = t.Dan_WMC
            });
            foreach (var item in parentModuleData)
            {
                model.CompanyItems.Add(new SelectListItem { Text = item.CompanyName, Value = item.CompanyId.ToString() });
            }
            #endregion


            #region 抄表员信息
            var parentModuleDataa = MeterReaderService.MeterReaders.Where(t => t.IsDeleted == false)
            .Select(t => new AreaModel
            {
                ChaoBiao_ID = t.Id,
                CHao_B_Name = t.Chao_BYMC
            });
            foreach (var item in parentModuleDataa)
            {
                model.ChaoBiaoItems.Add(new SelectListItem { Text = item.CHao_B_Name, Value = item.ChaoBiao_ID.ToString() });
            }
            #endregion
        }
    }
}
